package com.jkoss.wine.weekly.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jkoss.base.controller.BaseController;
import com.jkoss.common.util.CommonUtil;
import com.jkoss.common.vo.DwzPageBean;
import com.jkoss.wine.system.entity.Department;
import com.jkoss.wine.system.entity.MerchantEmployees;
import com.jkoss.wine.system.entity.MessageNotification;
import com.jkoss.wine.system.entity.Role;
import com.jkoss.wine.system.service.IDepartmentService;
import com.jkoss.wine.system.service.IMerchantEmployeesService;
import com.jkoss.wine.system.service.IMessageNotificationService;
import com.jkoss.wine.system.service.IRoleService;
import com.jkoss.wine.warehouse.vo.WareTransferOrderVoExcel;
import com.jkoss.wine.weekly.entity.Monthly;
import com.jkoss.wine.weekly.service.IMonthlyService;
import com.jkoss.wine.weekly.vo.MonthlyVo;

import cn.afterturn.easypoi.entity.vo.NormalExcelConstants;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;

/**
 * 月报 前端控制器
 * 
 * @Author Jason
 * @Version 1.0, 2018-12-05
 * @See
 * @Since com.jkoss.wine.weekly.controller
 * @Description: TODO
 */
@Controller
@RequestMapping("/weekly/monthly")
public class MonthlyController extends BaseController {

	@Autowired
	private IMonthlyService iMonthlyService;
	@Autowired
	private IMerchantEmployeesService iMerchantEmployeesService;
	@Autowired
	private IDepartmentService iDepartmentService;
	@Autowired
	private IRoleService iRoleService;
	@Autowired
	private IMessageNotificationService iMessageNotificationService;

	@RequestMapping("/list")
	@RequiresPermissions("/weekly/monthly/list")
	public String list(String eid, String did, String startTime, String endTime, DwzPageBean dwzPageBean, ModelMap map, HttpServletRequest request, HttpServletResponse response) throws Exception {
		dwzPageBean.getCountResultMap().put("eid", eid);
		dwzPageBean.getCountResultMap().put("did", did);
		dwzPageBean.getCountResultMap().put("startTime", startTime);
		dwzPageBean.getCountResultMap().put("endTime", endTime);
		Wrapper wrapper = Condition.create().ne("w.del", 1);
		if (!CommonUtil.isBlank(eid)) {
			wrapper.eq("w.meid", eid);
		}
		if (!CommonUtil.isBlank(did)) {
			wrapper.eq("w.dmid", did);
		}
		if (!CommonUtil.isBlank(startTime)) {
			wrapper.ge("w.tltm", startTime);
		}
		if (!CommonUtil.isBlank(endTime)) {
			wrapper.le("w.tltm", CommonUtil.dateLastTime(endTime));
		}

		// 字段排序
		if (!CommonUtil.isBlank(dwzPageBean.getOrderField()) && !CommonUtil.isBlank(dwzPageBean.getOrderDirection())) {
			dwzPageBean.getCountResultMap().put("orderField", dwzPageBean.getOrderField());
			dwzPageBean.getCountResultMap().put("orderDirection", dwzPageBean.getOrderDirection());
			wrapper.orderBy(dwzPageBean.getOrderField(), CommonUtil.isEquals(dwzPageBean.getOrderDirection(), "asc"));
		} else {
			wrapper.orderBy("w.add_time", false);
		}
		// 下级员工,并且相同部门
		Set set = iRoleService.selectChildren(getUserId());
		wrapper.in("w.meid", set);
		Page resultPage = iMonthlyService.selectVoByPage(dwzPageBean.toPage(), wrapper);
		map.put("dwzPageBean", dwzPageBean.toDwzPageBean(resultPage));

		MerchantEmployees merchantEmployees = iMerchantEmployeesService.selectById(getUserId());
		map.put("merchantEmployees", merchantEmployees);
		Wrapper meWrapper = Condition.create().ne("del", 1);
		List<MerchantEmployees> employees = iMerchantEmployeesService.selectList(meWrapper);
		map.put("employees", employees);
		Wrapper dmWrapper = Condition.create().ne("del", 1);
		List<Department> departments = iDepartmentService.selectList(dmWrapper);
		map.put("departments", departments);

		Wrapper updatewrapper = Condition.create().eq("meid", getUserId()).eq("type", 3);
		MessageNotification entity = new MessageNotification();
		// 类型：1-通知公告未读提醒、2-周报、3-月报未读及未提交提醒、4-新客户资源分配提醒、5-资源客户未沟通提醒
		entity.setType(3);
		// 是否已读：0-未读、1-已读
		entity.setIsread(1);
		iMessageNotificationService.update(entity, updatewrapper);

		return "weekly/monthly/list";
	}

	@RequestMapping("/toInsert")
	@RequiresPermissions("/weekly/weekly/toInsert")
	public String toInsert(ModelMap map, HttpServletRequest request, HttpServletResponse response) throws Exception {
		Wrapper rWrapper = Condition.create().ne("del", 1);
		MerchantEmployees merchantEmployees = iMerchantEmployeesService.selectById(getUserId());
		if (!CommonUtil.isBlank(merchantEmployees.getDmid())) {
			rWrapper.eq("dmid", merchantEmployees.getDmid());
		} else {
			throw new Exception("先选择部门");
		}
		List<Role> list = iRoleService.selectList(rWrapper);
		map.put("list", list);
		return "weekly/monthly/edit";
	}

	@RequestMapping("/insert")
	@RequiresPermissions("/weekly/monthly/toInsert")
	@ResponseBody
	public Object insert(@Valid Monthly weekly, HttpServletRequest request, HttpServletResponse response) {
		// 制表人
		weekly.setMeid(getUserId());
		// 制表时间
		weekly.setTltm(CommonUtil.getDate());
		// 部门id
		MerchantEmployees e = iMerchantEmployeesService.selectById(getUserId());
		weekly.setDmid(e.getDmid());
		// 获取当前时间
		weekly.setAddTime(CommonUtil.getDate());
		// 获取当前操作人，当操作人为null时，表示自动录入
		weekly.setOperator(getUserId());
		// 是否删除：0-未删除、1-已删除、2-不能删除
		weekly.setDel(0);
		if (iMonthlyService.insert(weekly)) {
			return ajaxSuccess();
		} else {
			return ajaxError();
		}
	}

	@RequestMapping("/toUpdate")
	@RequiresPermissions("/weekly/monthly/toUpdate")
	public String toUpdate(String id, ModelMap map, HttpServletRequest request, HttpServletResponse response) {
		Wrapper rWrapper = Condition.create().ne("del", 1);
		List<Role> list = iRoleService.selectList(rWrapper);
		map.put("list", list);
		map.put("record", iMonthlyService.selectById(id));
		return "weekly/monthly/edit";
	}

	@RequestMapping("/update")
	@RequiresPermissions("/weekly/monthly/toUpdate")
	@ResponseBody
	public Object update(@Valid Monthly weekly, HttpServletRequest request, HttpServletResponse response) {
		if (iMonthlyService.updateById(weekly)) {
			return ajaxSuccess();
		} else {
			return ajaxError();
		}
	}

	@RequestMapping("/delete")
	@RequiresPermissions("/weekly/monthly/delete")
	@ResponseBody
	public Object delete(String[] id, HttpServletRequest request, HttpServletResponse response) {
		List<Monthly> list = new ArrayList();
		for (String string : id) {
			Monthly entity = new Monthly();
			entity.setId(string);
			// 是否删除：0-未删除、1-已删除、2-不能删除
			entity.setDel(1);
			list.add(entity);
		}
		if (iMonthlyService.updateBatchById(list)) {
			return ajaxSuccess();
		} else {
			return ajaxError();
		}
	}

	/**
	 * 订单详情
	 * 
	 * @param id
	 * @param map
	 * @param str
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/details")
	@RequiresPermissions("/weekly/monthly/details")
	public String details(String id, ModelMap map, String str, HttpServletRequest request, HttpServletResponse response) {
		MonthlyVo details = iMonthlyService.selectVoById(id);
		map.put("record", details);
		Wrapper rWrapper = Condition.create().ne("del", 1);
		List<Role> list = iRoleService.selectList(rWrapper);
		map.put("list", list);
		return "weekly/monthly/details";
	}

	/**
	 * 导出EXCEL
	 * 
	 * @param map
	 * @param dwzPageBean
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/export")
	@RequiresPermissions("/weekly/monthly/export")
	public String export(ModelMap map, DwzPageBean dwzPageBean, HttpServletRequest request, HttpServletResponse response) {
		// 从数据库中查找数据
		Wrapper wrapper = Condition.create().ne("w.del", 1);
		// 根据用户id获取角色
		// boolean isDirector = true;
		// List<Role> roles = getRoleList();
		// for (Role role : roles) {
		// if ("运营主管".equals(role.getName())) {
		// isDirector = false;
		// }
		// }
		// if (isDirector) {
		// wrapper.eq("maid", getUserId());
		// }
		Page page = dwzPageBean.toPage();
		page.setSize(Page.NO_ROW_LIMIT);
		page.setCurrent(1);
		List list = iMonthlyService.selectVoByPage(page, wrapper).getRecords();
		ExportParams params = new ExportParams(null, "月报", ExcelType.XSSF);
		map.put(NormalExcelConstants.DATA_LIST, list); // 数据集合
		map.put(NormalExcelConstants.CLASS, MonthlyVo.class);// 导出实体
		map.put(NormalExcelConstants.PARAMS, params);// 参数
		map.put(NormalExcelConstants.FILE_NAME, "月报");// 文件名称
		return NormalExcelConstants.EASYPOI_EXCEL_VIEW;// View名称
	}
}
